﻿using System;
using System.Text;
using RabbitMQ.Client.Events;
using RabbitMQDemo.Common;

namespace RabbitMQDemo.Consumer
{
    public class Simple
    {
        private const string QueueName = "simple_queue";

        public static void Receive(string[] args)
        {
            using var connection = MQClient.GetConnection();
            using var channel = connection.CreateModel();

            // 声明队列
            channel.QueueDeclare(queue: QueueName, durable: false, exclusive: false, autoDelete: false, arguments: null);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                Console.WriteLine($"[Simple]received：{message}");
            };

            /*
             * 消费消息
             *  queue: 队列名称
             *  autoAck: 是否自动回复Ack
             *  consumerTag: 消费者标签，用来区分多个消费者
             *  noLocal: 设置为true，表示不能将同一个Conenction中生产者发送的消息传递给这个Connection中的消费者
             *  exclusive: 设置是否排他
             *  arguments: 消费者的参数
             *  consumer: 消费者
             */
            channel.BasicConsume(queue: QueueName, autoAck: true, consumerTag: "testConsumer", noLocal: false, exclusive: false, arguments: null, consumer: consumer);

            Console.WriteLine("按任意键退出");
            Console.ReadKey();
        }
    }
}
